﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DiscoveryLogic.Analytics.BusinessLogic.Measures;
using DiscoveryLogic.Analytics.DataObjects;
using DiscoveryLogic.Analytics.DataObjects.Networks;

namespace DiscoveryLogic.Analytics.BusinessLogic.Clusters
{
    public class NetworkPathClusterWorker
    {
        private Network _Network;

        public NetworkPathClusterWorker(Network network)
        {
            this._Network = network;
        }

        public void ClusterBasedOnCentrality(int clusterSizeThreshold)
        {
            Dictionary<int, NetworkCluster> clusters = new Dictionary<int, NetworkCluster>();
            Dictionary<int, List<EntityBase>> connectedEntities = this._Network.GroupConnectedEntities();
            List<EntityBase> orphanedEntities=new List<EntityBase>();
            foreach (int groupID in connectedEntities.Keys)
            {
                List<EntityBase> entities = connectedEntities[groupID];
                if (entities.Count > clusterSizeThreshold)
                {
                    List<Link> links = Network.GetLinksWithinEntities(this._Network.Links, entities);
                    Graph g = new Graph(entities, links);
                    BetweennessCentralityMeasure bcWorker = new BetweennessCentralityMeasure();
                    Dictionary<Guid, double> bcMeasures = bcWorker.GetVerticeMeasure(g);
                    List<EntityBase> orphanedEntities1 = this.SplitEntitiesByBCScores(entities, g, bcMeasures, ref clusters);
                    if(orphanedEntities1.Count>0)
                        orphanedEntities.AddRange(orphanedEntities1);
                }
                else
                {
                    orphanedEntities.AddRange(entities);
                }
            }
            if(orphanedEntities.Count>0)
            {
                int clusterID = clusters.Count + 1;
                NetworkCluster cluster = this.InitCluster(clusterID, 0, orphanedEntities);
                clusters.Add(cluster.ClusterID, cluster);
            }

            List<NetworkCluster> clusterList = this.UpdateClusterParentChildRelations(clusters);
            NetworkCluster.Save(this._Network.NetworkName, clusterList);
        }

        private List<EntityBase> SplitEntitiesByBCScores(
            List<EntityBase> entities, Graph g, 
            Dictionary<Guid, double> bcMeasures, 
            ref Dictionary<int, NetworkCluster> clusters)
        {
            List<EntityBase> orphanedEntities=new List<EntityBase>();
            List<EntityBase> bridgeEntities=new List<EntityBase>();
            double maxScore = 0;
            foreach(Guid vid in bcMeasures.Keys)
            {
                double bcScore = bcMeasures[vid];
                if(bcScore>maxScore)
                {
                    EntityBase entity = g.Vertices[vid].Tag;
                    bridgeEntities=new List<EntityBase>();
                    bridgeEntities.Add(entity);
                    maxScore = bcScore;
                }
                else if(bcScore==maxScore)
                {
                    EntityBase entity = g.Vertices[vid].Tag;
                    bridgeEntities.Add(entity);
                }
            }
            if(bridgeEntities.Count>0)
            {
                foreach(EntityBase bridge in bridgeEntities)
                {
                    orphanedEntities.Add(bridge);
                    entities.Remove(bridge);
                }
                List<Link> links = Network.GetLinksWithinEntities(this._Network.Links, entities);
                Network net=new Network("", entities, links);
                Dictionary<int, List<EntityBase>> connectedComponents = net.GroupConnectedEntities();
                List<EntityBase> orphanedEntities2 =new List<EntityBase>();
                foreach(int groupID in connectedComponents.Keys)
                {
                    List<EntityBase> entities1 = connectedComponents[groupID];
                    if (entities1.Count > 1)
                    {
                        NetworkCluster newCluster = this.InitCluster(
                            clusters.Count + 1, 0, entities1);
                        clusters.Add(newCluster.ClusterID, newCluster);
                    }
                    else
                    {
                        orphanedEntities2.AddRange(entities1);
                    }
                }
                if(orphanedEntities2.Count>0)
                {
                    NetworkCluster newCluster = this.InitCluster(
                            clusters.Count + 1, 0, orphanedEntities2);
                    clusters.Add(newCluster.ClusterID, newCluster);
                }
            }
            else
            {
                NetworkCluster newCluster = this.InitCluster(clusters.Count + 1, 0, entities);
                clusters.Add(newCluster.ClusterID, newCluster);
            }
            return orphanedEntities;
        }

        private NetworkCluster InitCluster(
            int clusterID, int parentClusterID,
            List<EntityBase> childEntities)
        {
            NetworkCluster cluster = new NetworkCluster(clusterID, parentClusterID, "");
            if (childEntities != null && childEntities.Count > 0)
            {
                cluster.ChildEntities.AddRange(childEntities);
            }
            return cluster;
        }


        private List<NetworkCluster> UpdateClusterParentChildRelations(Dictionary<int, NetworkCluster> clusters)
        {
            Dictionary<int, List<int>> clusterChildClusters = new Dictionary<int, List<int>>();
            foreach (NetworkCluster cluster in clusters.Values)
            {
                if (clusterChildClusters.ContainsKey(cluster.ParentClusterID))
                {
                    List<int> childClusterIDs = clusterChildClusters[cluster.ParentClusterID];
                    if (!childClusterIDs.Contains(cluster.ClusterID))
                        childClusterIDs.Add(cluster.ClusterID);
                    clusterChildClusters[cluster.ParentClusterID] = childClusterIDs;
                }
                else
                {
                    List<int> childClusterIDs = new List<int>();
                    childClusterIDs.Add(cluster.ClusterID);
                    clusterChildClusters.Add(cluster.ParentClusterID, childClusterIDs);
                }
            }
            foreach (int clusterID in clusters.Keys)
            {
                NetworkCluster cluster = clusters[clusterID];
                if (clusterChildClusters.ContainsKey(clusterID))
                {
                    List<NetworkCluster> childClusters = new List<NetworkCluster>();
                    List<int> childClusterIDs = clusterChildClusters[clusterID];
                    foreach (int childClusterID in childClusterIDs)
                    {
                        childClusters.Add(clusters[childClusterID]);
                    }
                    cluster.ChildClusters = childClusters;
                }
            }
            List<NetworkCluster> clusterList = clusters.Values.ToList();
            return clusterList;
        }
    }
}
